﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
    
    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Session["Theme"] == null)
            Session["Theme"] = GlobalValues.DefaultTheme;

        this.Theme = "BlueTheme";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.Title = "MaxBlox";
        tb_password.TextMode = TextBoxMode.Password;
        if (ConfigurationManager.AppSettings["show_company_on_login"] != null) // Added by 'Imran Gani' on 05-May-2014.
            if (ConfigurationManager.AppSettings["show_company_on_login"].Trim() != "")
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["show_company_on_login"].ToString()))
                {
                    tr_company.Visible = false;
                    lbl_LoginText.Text = "&nbsp;Please enter your User Name &amp; Password";
                    if (Request.QueryString["continue"] == null && Request.UrlReferrer != null && Request.UrlReferrer.ToString() != "")
                        if (Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf('/')) != Request.UrlReferrer.ToString().Substring(0, Request.UrlReferrer.ToString().LastIndexOf('/')))
                        {
                            hl_back.HRef = Request.UrlReferrer.ToString();
                            hl_back.Visible = true;
                        }
                }
                        
        if (!Page.IsPostBack) checkAutoLogin();
        tb_company.Focus();
    }
    private string getSecureModeURL(string url)//included by sanal on 27th Jan 09
    {
        if (url.StartsWith("http:") == true)
        {
            return "https" + url.Remove(0, 4);
        }
        else
        {
            return url;
        }
    }
    protected void bt_login_Click(object sender, EventArgs e)
    {
        AuditLog AL = new AuditLog();
        Session.Remove("dbcon");
        security hds = new security(tb_userid.Text);
        if (!hds.checkLoginAccessDelay()) // Added by 'Imran Gani' on 25-Nov-2013.
        {
            lb_message.Text = "Login failed. Temporarily access denied.";
            div_err_msg.Visible = true;
            return;
        }
        if (ConfigurationManager.AppSettings["show_company_on_login"] != null) // Added by 'Imran Gani' on 05-May-2014.
            if (ConfigurationManager.AppSettings["show_company_on_login"].Trim() != "")
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["show_company_on_login"].ToString()))
                {
                    HDDatabase HDD = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
                    tb_company.Text = HDD.GetColumnValue("select company_id from ngcompanyuser where user_id = '" + tb_userid.Text + "';");
                    HDD = null;
                }

        #region Added by 'Imran Gani' on 20-Aug-2014, to choose the company when user attached to multiple companies
        bool IsCompanyChooser=false;
        if (ConfigurationManager.AppSettings["company_chooser"] != null)
            if (ConfigurationManager.AppSettings["company_chooser"].Trim() != "")
                IsCompanyChooser = Convert.ToBoolean(ConfigurationManager.AppSettings["company_chooser"].ToString());
                
        bool isValidLogin = true;
        LoginProcess LP = new LoginProcess();
        if (LP.UserValidate(tb_company.Text, tb_userid.Text, tb_password.Text))
        {
            if (!IsCompanyChooser)
            {
                string sCompanyURL = LP.getCompanyHomePage(tb_company.Text, tb_userid.Text, tb_password.Text);
                if (sCompanyURL != "")
                    Response.Redirect(sCompanyURL);
                else
                    isValidLogin = false;
            }
            else
            {
                Session["company_id"] = tb_company.Text;
                Session["userid"] = tb_userid.Text;
                Response.Redirect("companylist.aspx?clist=1");
            }
        }
        else
            isValidLogin = false;
        
        if(!isValidLogin)
        {
            Session["dbcon"] = Session["servercon"];
            AL.logUserInModel(tb_company.Text, tb_userid.Text, false); // Modified by 'Imran Gani' on 25-Nov-2013.
            AL = null;
            hds.HandleLoginAttempts(tb_company.Text, tb_userid.Text, tb_password.Text); // Added by 'Imran Gani' on 25-Nov-2013.
            lb_message.Text = (hds.Message == null || hds.Message == "" ? "Login failed, please try again" : hds.Message);
            div_err_msg.Visible = true;
        }
        #endregion

        #region Old Code Cemmented by 'Imran Gani' on 20-Aug-2014
        //if (hds.SaaSUserAuthenticate(tb_company.Text, tb_userid.Text, tb_password.Text))
        //{
        //    HDDatabase hddb = new HDDatabase();
        //    //string strUserFullName = hddb.GetColumnValue("select isnull(first_name,'') + ' ' + isnull(last_name,'') from sy_usr where user_id='" + tb_userid.Text.Replace("'", "''") + "'");
        //    DataTable dtUsertable = new DataTable(); string strUserFullName = ""; string strUserRole = ""; string strRoleId = ""; string strWelcomeTitle = "";
        //    dtUsertable = hddb.GetDataTable("select isnull(first_name,'') + ' ' + isnull(last_name,''),af_row_id,locale from sy_usr where user_id='" + tb_userid.Text.Replace("'", "''") + "'");
        //    if (dtUsertable != null)
        //        if (dtUsertable.Rows.Count > 0)
        //        {
        //            strUserFullName = HttpUtility.HtmlEncode(dtUsertable.Rows[0][0].ToString());
        //            HttpContext.Current.Session["userlocale"] = dtUsertable.Rows[0]["locale"].ToString();
        //            DataRow drRole = hddb.GetTableRow("select af_row_id,role_name from sy_rol where af_row_id='" + hddb.GetColumnValue("select role_id from sy_usr_rol where user_id='" + dtUsertable.Rows[0][1].ToString() + "'") + "'");
        //            if (drRole != null)
        //            {
        //                strRoleId = drRole["af_row_id"].ToString();
        //                strUserRole = drRole["role_name"].ToString();                        
        //                //strUserRole = hddb.GetColumnValue("select role_name from sy_rol where af_row_id='" + hddb.GetColumnValue("select role_id from sy_usr_rol where user_id='" + dtUsertable.Rows[0][1].ToString() + "'") + "'");
        //            }
        //        }
        //    HttpContext.Current.Session["user_name"] = strUserFullName;
        //    HttpContext.Current.Session["user_role"] = strUserRole;
        //    HttpContext.Current.Session["userid"] = tb_userid.Text;
        //    HttpContext.Current.Session["roleid"] = strRoleId;
            
            
        //    string sTheme = "";
        //    DataTable dtUser = hddb.GetDataTable("select * from sy_usr");
        //    if (dtUser.Columns.Contains("theme"))
        //    {
        //        DataRow[] drr = dtUser.Select("user_id='" + tb_userid.Text.Replace("'", "''").Trim() + "'");
        //        if (drr.Length > 0)
        //        {
        //            sTheme = drr[0]["theme"].ToString().Trim();
        //            Session["user_afrowid"] = dtUser.Columns.Contains("af_row_id") == true ? drr[0]["af_row_id"].ToString() : Session["userid"].ToString();//included by sanal
        //            Session["custodian"] = drr[0]["custodian_filter"].ToString();
        //            //hds.Insert_AppVariable("current_userafrowid", HttpContext.Current.Session["user_afrowid"].ToString());
        //        }
        //    }

        //    //hds.Insert_AppVariable("current_userid", HttpContext.Current.Session["userid"].ToString());
        //    //hds.Insert_AppVariable("current_username", HttpContext.Current.Session["user_name"].ToString());

        //    strWelcomeTitle = CommonFunctions.replaceSystemVariables(hddb.getAcrMemValue("c5016bbf3100ab6f", "WT")); // Added by 'Imran Gani' on 24-Dec-2012, for dynamic welcome title.
        //    HttpContext.Current.Session["Welcome_Title"] = strWelcomeTitle;

        //    if (sTheme == "")
        //        HttpContext.Current.Session["Theme"] = GlobalValues.DefaultTheme;
        //    else
        //        HttpContext.Current.Session["theme"] = sTheme;
        //    AL.logUserInCompany();
        //    AL.logUserInModel(tb_company.Text, tb_userid.Text, true); // Added by 'Imran Gani' on 25-Nov-2013.
        //    AL = null;
        //    //create logo file in server
        //    createCustomLogo();
        //    //Response.Redirect("welcome.aspx?id=default");
            
        //    // Added by 'Imran Gani' 13-Mar-2013, to get the continue URL of requested page.
        //    string sUrlContinue = HttpUtility.UrlDecode(Request.QueryString["continue"] != null ? Request.QueryString["continue"].ToString() : "");
        //    #region Old Message Handling, Commented by 'Imran Gani' on 20-June-2013
        //    //string[] mesgs = getUserMessages();
        //    //if (mesgs.Length > 0)
        //    //{
        //    //    Response.Clear();
        //    //    //string mesContent = "<html><head><link href='App_Themes/" + Session["theme"].ToString() + "/" + Session["theme"].ToString().ToLower().Replace("theme", "") + ".css' type='text/css' rel='stylesheet' /></head><body><div style='width:100%;text-align:center;height:100%;border=solid 0px #FF0000;'><div style='width:60%;margin:0 auto;text-align:left;border=solid 1px #EAEAEA;margin-top:50px;'><div class='Grid_Header'>Messages<div><div class='Grid_Header'>$message$<div></div></div></body></html>";
        //    //    string mesContent = ReadHtmFile("messages.htm");
        //    //    mesContent = mesContent.Replace("$message$", HttpUtility.HtmlEncode(mesgs[0].Replace("\r\n","</br>")));
        //    //    mesContent = mesContent.Replace("$theme$", "App_Themes/" + Session["theme"].ToString() + "/" + Session["theme"].ToString().ToLower().Replace("theme", "") + ".css");
        //    //    mesContent = mesContent.Replace("$continuelink$", sUrlContinue != "" ? sUrlContinue : navigate2Home()); // Modified by 'Imran Gani' 13-Mar-2013, to redirect a page of necessary URL
        //    //    Response.Write(mesContent);
        //    //    Response.End();
        //    //}
        //    #endregion
        //    string msg_id = hddb.GetColumnValue("select af_row_id from sy_messages where active=1 order by modified_at desc;"); // Modified by 'Imran Gani' on 18-Jul-2013, to get recently modified data.
        //    if (msg_id != "") // Added by 'Imran Gani' on 20-June-2013, to handle message.
        //        sUrlContinue = "msg.aspx?id=" + msg_id + "&url=" + HttpUtility.UrlEncode((sUrlContinue != "" ? sUrlContinue : navigate2Home())); 
        //        //Response.Redirect("msg.aspx?id=" + msg_id + "&url=" + HttpUtility.UrlEncode((sUrlContinue != "" ? sUrlContinue : navigate2Home())));
        //    else
        //        sUrlContinue = (sUrlContinue != "" ? sUrlContinue : navigate2Home()); // Modified by 'Imran Gani' 13-Mar-2013, to redirect a page of necessary URL
        //        //Response.Redirect(sUrlContinue != "" ? sUrlContinue : navigate2Home(), false); // Modified by 'Imran Gani' 13-Mar-2013, to redirect a page of necessary URL
        //    checkPasswordValidityPeriod(sUrlContinue); // Added by 'Imran Gani' on 25-Nov-2013.
        //}
        //else
        //{
        //    Session["dbcon"] = Session["servercon"];
        //    AL.logUserInModel(tb_company.Text, tb_userid.Text, false); // Modified by 'Imran Gani' on 25-Nov-2013.
        //    AL = null;
        //    hds.HandleLoginAttempts(tb_company.Text, tb_userid.Text, tb_password.Text); // Added by 'Imran Gani' on 25-Nov-2013.
        //    lb_message.Text = hds.Message;
        //    div_err_msg.Visible = true;
        //}
        #endregion
    }
    public string ReadHtmFile(string fileName)
    {
        fileName = Server.MapPath("") + "/" + fileName;
        string content;
        FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(stream);
        content = reader.ReadToEnd();
        reader.Close();
        return content;
    }
    private void createCustomLogo()
    {
        security s = new security();
        string fName="";string ext="";
        if (s.createCustomLogo(ref fName, ref ext))
            Session["hasCustomLogo"] = "1";
        else
            Session["hasCustomLogo"] = "0";
        s = null;
    }
    private string navigate2Home()
    {
        Navigator ng = new Navigator();
        string retrn = ng.getUserHomePage();
        ng = null;
        return retrn;
    }
    private string[] getUserMessages()
    {
        HDDatabase hdd = new HDDatabase();
        ArrayList alRet = new ArrayList();
        try
        {
            if (HttpContext.Current.Session["user_afrowid"] == null) return new string[] { };
            if (HttpContext.Current.Session["user_afrowid"].ToString().Trim() == "") return new string[] { };
            DataTable dtMes = new DataTable();
            //dtMes = hdd.GetDataTable("select * from sy_messages where active=1 and audience_members like '%" + HttpContext.Current.Session["user_afrowid"].ToString() + "%'");
            //fetch regardless of message type now
            dtMes = hdd.GetDataTable("select * from sy_messages where active=1 and ((audience_members like '%" + HttpContext.Current.Session["user_afrowid"].ToString() + "%' or audience_members like '%" + HttpContext.Current.Session["roleid"].ToString() + "%') or audience_type='ALL')");
            if (dtMes != null)
            {
                if (dtMes.Rows.Count > 0)
                {
                    if (dtMes.Rows[0]["message"].ToString().Length > 0)
                        alRet.Add(dtMes.Rows[0]["message"].ToString());
                }
            }
            dtMes = null;
            
        }
        catch (Exception ee)
        {
            LogWriter.WriteLog("Error " + ee.Message + " in getUserMessages Function");
        }
        finally
        {
            hdd = null;
        }
        return (String[])alRet.ToArray(typeof(string));
    }
    private void checkAutoLogin()
    {
        try
        {
            if (ConfigurationManager.AppSettings["windows_authentication"] == null || ConfigurationManager.AppSettings["windows_authentication"].Trim() == "" || !Convert.ToBoolean(ConfigurationManager.AppSettings["windows_authentication"].ToString()))
            {
                //string filePath = Server.MapPath(".") + "\\MaxBloxConfig.ini";
                string filePath = "C:" + "\\MaxBloxConfig.ini";
                string company = ""; string usrName = ""; string pwd = "";
                if (File.Exists(filePath))
                {
                    StreamReader sr = new StreamReader(filePath);
                    string temp = ""; int pos = 0;
                    while (!sr.EndOfStream)
                    {
                        temp = sr.ReadLine();
                        if (temp.ToLower().IndexOf("company=") > -1)
                        {
                            pos = temp.IndexOf("=");
                            company = temp.Substring(pos + 1, temp.Length - pos - 1);
                        }
                        if (temp.ToLower().IndexOf("user=") > -1)
                        {
                            pos = temp.IndexOf("=");
                            usrName = temp.Substring(pos + 1, temp.Length - pos - 1);
                        }
                        if (temp.ToLower().IndexOf("password=") > -1)
                        {
                            pos = temp.IndexOf("=");
                            pwd = temp.Substring(pos + 1, temp.Length - pos - 1);
                        }
                    }
                    sr.Close();
                    sr = null;
                    if (company.Length > 0 && usrName.Length > 0 && pwd.Length > 0)
                    {
                        tb_company.Text = company; tb_userid.Text = usrName; tb_password.Text = pwd;
                        bt_login_Click(null, null);
                    }
                }
            }
            else
            {
                if (ConfigurationManager.AppSettings["windows_authentication"].Trim() != "")
                    if (Convert.ToBoolean(ConfigurationManager.AppSettings["windows_authentication"].ToString()))
                    {
                        string SSOUserID = HttpContext.Current.User.Identity.Name; // To get the currrent windows user (enable windows authentication in IIS)
                        HDDatabase HDD = new HDDatabase();
                        if (Session["servercon"] != null)
                            if (Session["servercon"].ToString() != "")
                                HDD = new HDDatabase(Session["servercon"].ToString());
                        DataRow drSSO = HDD.GetTableRow("select usr.* from ngcompanyuser usr, sy_mb_sso sso where usr.af_row_id = sso.user_id and sso.sso_user_id = '" + SSOUserID + "' and usr.company_id = (select company_id from ngcompany where af_row_id = sso.company_id);");
                        if (drSSO != null)
                        {
                            tb_company.Text = drSSO["company_id"].ToString();
                            tb_userid.Text = drSSO["user_id"].ToString();
                            tb_password.Text = security.decrypt(drSSO["password"].ToString());
                            bt_login_Click(null, null);
                        }
                        HDD = null;
                    }
            }
        }
        catch (Exception ee)
        {
            LogWriter.WriteLog("Error " + ee.Message + " in checkAutoLogin Function");
        }
    }
    protected void tb_userid_TextChanged(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// To check Password Validity Period, when user login.
    /// </summary>
    /// <param name="sUrlContinue">URL to continue.</param>
    // Added by 'Imran Gani' on 25-Nov-2013.
    private void checkPasswordValidityPeriod(string sUrlContinue)
    {
        HDDatabase hdd = new HDDatabase();
        DataTable dt_pwdSecurityLog = new DataTable();
        string sRecentPwdLogDate;
        try
        {
            string svalidity_period = hdd.GetColumnValue("select mem_value2 from sy_acr_mem where acr_id = '21597547e2b0fa68' and mem_id = 'validity_period' and af_row_id = 'a5cd5d2f7aa7fa0f' and mem_value1 = 'enabled';");
            if (string.IsNullOrEmpty(svalidity_period) || svalidity_period == "0")
                Response.Redirect(sUrlContinue);
            else
            {
                sRecentPwdLogDate = hdd.GetColumnValue("select [created_at] from [sy_password_security_log] where [applies_to] = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "' order by [created_at] desc;");
                if (string.IsNullOrEmpty(sRecentPwdLogDate))
                {
                    AuditLog AL = new AuditLog();
                    AL.WritePasswordSecurityLog(Session["user_afrowid"].ToString(), Session["user_afrowid"].ToString(), security.encrypt(tb_password.Text), "Initiated log");
                    AL = null;
                    Response.Redirect(sUrlContinue);
                }
                else
                {
                    DateTime RecentLogCreatedAt = Convert.ToDateTime(sRecentPwdLogDate);
                    DateTime CurrentDate = DateTime.Now.ToUniversalTime();
                    TimeSpan difference = CurrentDate.Subtract(RecentLogCreatedAt);
                    int TotalDays = Convert.ToInt32(difference.TotalDays);
                    if (TotalDays < Convert.ToInt32(svalidity_period))
                        Response.Redirect(sUrlContinue);
                    else
                    {
                        Response.Redirect("changepassword.aspx?mn=bc98f78ad064743a&pgs_id=335dea653698e7a7&c_url=" + HttpUtility.UrlEncode(sUrlContinue) + "&ViewMode=content");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Default: checkPasswordValidityPeriod: Error: " + ex.Message);
        }
        finally
        {
            dt_pwdSecurityLog.Dispose();
        }
    }
}
